package com.easytouch.vmhdl.presenter;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Build;
import android.os.SystemClock;

import com.easytouch.core.DriverThread;
import com.easytouch.core.model.ColumnModel;
import com.easytouch.core.utils.FileTools;
import com.easytouch.core.utils.Log;
import com.easytouch.core.utils.SDCardTools;
import com.easytouch.vmhdl.activity.ManagerActivity;
import com.easytouch.vmhdl.interfaces.IManagerAddView;
import com.easytouch.vmhdl.model.IManagerAddModel;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by gulin on 2018/1/17.
 */

public class ManagerAddPresenter {

    private IManagerAddView mView;
    private IManagerAddModel mModel;
    private Log mLogger = new Log("ManagerAddPresenter.txt");

    public ManagerAddPresenter(IManagerAddView pView, IManagerAddModel pModel)
    {
        mView = pView;
        mModel = pModel;
    }

    public ArrayList<ColumnModel> getColumnDataByBox(final int pBox)
    {
        return mModel.getColumnDataByBox(pBox);
    }

    @SuppressLint("StaticFieldLeak")
    public void setColumnData(final int pBox, final int pColumn, final String pCode, final int pPrice, final int pMaxStock, final int pStock)
    {
        new AsyncTask<Void, Integer, Integer>()
        {
            @Override
            protected void onPreExecute()
            {
                mView.showProgressBar();
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                mView.progress(values[0]);
            }

            @Override
            protected Integer doInBackground(Void... params) {
                publishProgress(0);
                if(DriverThread.getInstance().mRoadInfo.containsKey(pBox)) {
                    ColumnModel[] modelArray = DriverThread.getInstance().mRoadInfo.get(pBox);
                    if (modelArray != null && pColumn <= modelArray.length) {
                        ColumnModel model = modelArray[pColumn - 1];
                        //修改商品ID和价格
                        byte[] bytes = null;
                        try {
                            bytes = DriverThread.makePriceAndCodeByteArray(pBox, pColumn, pPrice / 10, Integer.parseInt(pCode), false);
                        }
                        catch (NumberFormatException e)
                        {
                            return IManagerAddView.OPT_FAILED;
                        }
                        if(bytes != null)
                        {
                            DriverThread.getInstance().appendQueueData(bytes);
                            boolean isSuccess = false;
                            int times = 5;
                            while(times > 0) {
                                SystemClock.sleep(1000);
                                times--;
                                if(DriverThread.getInstance().cmdResult == DriverThread.CMD_ACK)
                                {
                                    isSuccess = true;
                                    break;
                                }
                            }
                            if(!isSuccess)
                            {
                                return IManagerAddView.OPT_FAILED;
                            }
                        }
                        publishProgress(33);
                        //修改商品库存
                        bytes = DriverThread.makeAddStockByteArray(pBox, pColumn, pStock);
                        if(bytes != null)
                        {
                            DriverThread.getInstance().appendQueueData(bytes);
                            boolean isSuccess = false;
                            int times = 5;
                            while(times > 0) {
                                SystemClock.sleep(1000);
                                times--;
                                if(DriverThread.getInstance().cmdResult == DriverThread.CMD_ACK)
                                {
                                    isSuccess = true;
                                    break;
                                }
                            }
                            if(!isSuccess)
                            {
                                return IManagerAddView.OPT_FAILED;
                            }
                        }
                        publishProgress(66);
                        //内存中更新下
                        model.goodsId = Integer.parseInt(pCode);
                        model.num = pStock;
                        model.maxStock = pMaxStock;
                        //写入到文件中
                        ManagerActivity.saveMaxConfig();
                        publishProgress(100);
                        SystemClock.sleep(100);
                    }
                }

                return IManagerAddView.OPT_SUCCESS;
            }

            @Override
            protected void onPostExecute(Integer result)
            {
                mView.hideProgressBar();
                mView.showMessage(result);
                super.onPostExecute(result);
            }
        }.execute();
    }

    @SuppressLint("StaticFieldLeak")
    public void addSingleBox(final int pBox)
    {
        new AsyncTask<Void, Integer, Integer>()
        {
            @Override
            protected void onPreExecute()
            {
                mView.showProgressBar();
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                mView.progress(values[0]);
            }

            @Override
            protected Integer doInBackground(Void... params) {

                if(DriverThread.getInstance().mRoadInfo.containsKey(pBox)) {
                    ColumnModel[] modelArray = DriverThread.getInstance().mRoadInfo.get(pBox);
                    for (int i = 0;i < modelArray.length;i++)
                    {
                        ColumnModel model = modelArray[i];
                        if(model.goodsId == DriverThread.COLUMN_DISABLED) //禁用的货道不更新
                        {
                            continue;
                        }
                        if(model.num == 99) //永久有货的货道不更新
                        {
                            continue;
                        }
                        byte[] bytes = DriverThread.makeAddStockByteArray(pBox, i + 1, model.maxStock);
                        if(bytes == null)
                        {
                            continue;
                        }
                        DriverThread.getInstance().appendQueueData(bytes);
                        int times = 5;
                        while(times > 0) {
                            SystemClock.sleep(1000);
                            times--;
                            if(DriverThread.getInstance().cmdResult == DriverThread.CMD_ACK)
                            {
                                break;
                            }
                        }
                        //内存中更新下
                        model.num = model.maxStock;
                        int percent = (int)((i + 1) / (float)modelArray.length * 100.0);
                        publishProgress(percent);
                    }
                    //写入到文件中
                    ManagerActivity.saveMaxConfig();
                    publishProgress(100);
                    SystemClock.sleep(100);
                }

                return IManagerAddView.OPT_SUCCESS;
            }

            @Override
            protected void onPostExecute(Integer result)
            {
                mView.hideProgressBar();
                mView.showMessage(result);
                super.onPostExecute(result);
            }
        }.execute();
    }

    @SuppressLint("StaticFieldLeak")
    public void addAllBox(final int pBox)
    {
        new AsyncTask<Void, Integer, Integer>()
        {
            @Override
            protected void onPreExecute()
            {
                mView.showProgressBar();
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                mView.progress(values[0]);
            }

            @Override
            protected Integer doInBackground(Void... params) {
                for (int j = 1; j <= 11; j++) {
                    if (DriverThread.getInstance().mRoadInfo.containsKey(pBox)) {
                        ColumnModel[] modelArray = DriverThread.getInstance().mRoadInfo.get(pBox);
                        for (int i = 0; i < modelArray.length; i++) {
                            ColumnModel model = modelArray[i];
                            if (model.goodsId == DriverThread.COLUMN_DISABLED) //禁用的货道不更新
                            {
                                continue;
                            }
                            if (model.num == 99) //永久有货的货道不更新
                            {
                                continue;
                            }
                            byte[] bytes = DriverThread.makeAddStockByteArray(pBox, i + 1, model.maxStock);
                            if (bytes == null) {
                                continue;
                            }
                            DriverThread.getInstance().appendQueueData(bytes);
                            int times = 5;
                            while (times > 0) {
                                SystemClock.sleep(1000);
                                times--;
                                if (DriverThread.getInstance().cmdResult == DriverThread.CMD_ACK) {
                                    break;
                                }
                            }
                            //内存中更新下
                            model.num = model.maxStock;
                            int percent = (int) ((i + 1) / (float) modelArray.length * 11 * 100.0);
                            publishProgress(percent);
                        }

                    }
                }
                //写入到文件中
                ManagerActivity.saveMaxConfig();
                publishProgress(100);
                SystemClock.sleep(100);
                return IManagerAddView.OPT_SUCCESS;
            }

            @Override
            protected void onPostExecute(Integer result)
            {
                mView.hideProgressBar();
                mView.showMessage(result);
                super.onPostExecute(result);
            }
        }.execute();
    }

    @SuppressLint("StaticFieldLeak")
    public void exportData()
    {
        new AsyncTask<Void, Integer, Integer>()
        {

            @Override
            protected void onPreExecute()
            {
                mView.showProgressBar();
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                mView.progress(values[0]);
            }

            @SuppressWarnings("unchecked")
            @Override
            protected Integer doInBackground(Void... params)
            {
                String usb = "/mnt/usb_storge"; // /mnt/udisk
                if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
                    usb = "/mnt/udisk";
                }
                String des = usb + "/exportData/addGoods/" + ManagerActivity.FILE_MAX_CONFIG_NAME;
                String src = ManagerActivity.FILE_MAX_CONFIG;
                File fileSrc = new File(src);
                File fileDes = new File(des);

                publishProgress(0);

                mLogger.i("exportData:" + des);

                if(!fileDes.exists())
                {
                    try
                    {
                        if(!fileDes.createNewFile())
                            return IManagerAddView.OPT_NO_UDISK;
                    }
                    catch (IOException e)
                    {
                        return IManagerAddView.OPT_NO_UDISK;
                    }
                }
                //首先将文件保存
                ManagerActivity.saveMaxConfig();
                publishProgress(50);
                //拷贝文件
                if(!FileTools.copyFile(src, des))
                {
                    return IManagerAddView.OPT_COPY_ERROR;
                }
                publishProgress(100);

                return IManagerAddView.OPT_SUCCESS;
            }

            @Override
            protected void onPostExecute(Integer result)
            {
                mView.hideProgressBar();
                mView.showMessage(result);
                super.onPostExecute(result);
            }

        }.execute();
    }

    @SuppressLint("StaticFieldLeak")
    public void importData()
    {
        new AsyncTask<Void, Integer, Integer>()
        {

            @Override
            protected void onPreExecute()
            {
                mView.showProgressBar();
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                mView.progress(values[0]);
            }

            @SuppressWarnings("unchecked")
            @Override
            protected Integer doInBackground(Void... params)
            {
                String usb = "/mnt/usb_storge"; // /mnt/udisk
                if(Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
                    usb = "/mnt/udisk";
                }
                String src = usb + "/exportData/addGoods/" + ManagerActivity.FILE_MAX_CONFIG_NAME;
                String des = ManagerActivity.FILE_MAX_CONFIG;
                File fileSrc = new File(src);
                //File fileDes = new File(des);

                publishProgress(0);

                mLogger.i("importData:" + src);

                if(!fileSrc.exists())
                {
                    return IManagerAddView.OPT_NO_FILE;
                }
                //拷贝文件
                if(!FileTools.copyFile(src, des))
                {
                    return IManagerAddView.OPT_COPY_ERROR;
                }
                //读取配置
                ManagerActivity.readMaxConfig(des, true);

                for (int j = 1; j <= 11; j++) {
                    if (DriverThread.getInstance().mRoadInfo.containsKey(j)) {
                        ColumnModel[] modelArray = DriverThread.getInstance().mRoadInfo.get(j);
                        for (int i = 0; i < modelArray.length; i++) {
                            ColumnModel model = modelArray[i];
                            //修改商品ID和价格
                            byte[] bytes = null;
                            try {
                                bytes = DriverThread.makePriceAndCodeByteArray(j, i, model.price / 10, model.goodsId, false);
                            }
                            catch (NumberFormatException e)
                            {
                                return IManagerAddView.OPT_FAILED;
                            }
                            if(bytes != null)
                            {
                                DriverThread.getInstance().appendQueueData(bytes);
                                boolean isSuccess = false;
                                int times = 5;
                                while(times > 0) {
                                    SystemClock.sleep(1000);
                                    times--;
                                    if(DriverThread.getInstance().cmdResult == DriverThread.CMD_ACK)
                                    {
                                        isSuccess = true;
                                        break;
                                    }
                                }
                                if(!isSuccess)
                                {
                                    return IManagerAddView.OPT_FAILED;
                                }
                            }
                            int percent = (int) ((i + 1) / (float) modelArray.length * 11 * 100.0);
                            publishProgress(percent);
                        }

                    }
                }
                //写入到文件中
                ManagerActivity.saveMaxConfig();
                publishProgress(100);
                SystemClock.sleep(100);

                return IManagerAddView.OPT_SUCCESS;
            }

            @Override
            protected void onPostExecute(Integer result)
            {
                mView.hideProgressBar();
                mView.showMessage(result);
                super.onPostExecute(result);
            }

        }.execute();
    }
}
